#include "stdafx.h"
#include "SOCK_Connector.h"

namespace Network
{	
	bool SOCK_Connector::connect_to_server(SOCK_Stream &stream, const INET_Addr &addr) {
		handle_ = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);

		if(handle_ == INVALID_SOCKET){
			fprintf(stdout, "Invalid socket\n");
			WSACleanup();
			return 1;
		}

		sockaddr_in clientSocket = *addr.Addr();
		int result = connect(handle_, (SOCKADDR *)&clientSocket, sizeof(clientSocket));
		
		if(result == SOCKET_ERROR){
			fprintf(stdout, "Error while connecting\n");
			WSACleanup();
			return false;
		} else if (result == 0) {
			stream.SetHandle((HANDLE)handle_);
			return true;
		} else {
			fprintf(stdout, "Unknown connect result => %d\n", result);
			return false;
		}
	}
}
